<?php
/**
 * created by zzy
 * date: 2017/12/26 11:30
 */

namespace App\Http\Admin\System\Models;
use App\Eloquent\Ygt\AssemblageMaterial;
use App\Eloquent\Ygt\Product;
use App\Eloquent\Ygt\ProductFields;
use DB;
use App\Eloquent\Ygt\Department;
use App\Eloquent\Ygt\Privilege;
use App\Eloquent\Ygt\PrivilegeAppnode;
use App\Eloquent\Ygt\PrivilegeAppindex;
use App\Eloquent\Ygt\OrderType;
use App\Eloquent\Ygt\ProcessOrdertype;
use App\Eloquent\Ygt\Process;
use App\Eloquent\Ygt\ProcessField;
use App\Eloquent\Ygt\ProcessFieldRelation;
use App\Eloquent\Ygt\ProcessFieldRelationSelect;
use App\Eloquent\Ygt\Category;
use App\Eloquent\Ygt\CategoryFields;
use App\Engine\Product as EngineProduct;

class Copy{

    /**
     * 复制部门
     * created by zzy
     * @param $companyId  当前厂id
     * @param $fromCompanyId  要复制的厂id
     */
    public static function department($companyId, $fromCompanyId)
    {
        $nowTime        = $_SERVER['REQUEST_TIME'];
        $where          = ['company_id'=>$fromCompanyId];
        $list           = Department::getList($where)->toArray();
        $data           = [];
        foreach( $list as $key=>$val )
        {
            $arr                 = $val;
            unset($arr['id']);
            $arr['company_id']  = $companyId;
            $arr['created_at']  = $nowTime;
            $arr['updated_at']  = $nowTime;
            $data[]              = $arr;
        }
        $table                   = 'ygt_department';
        DB::table($table)->where('company_id', $companyId)->delete();
        $result                 = DB::table($table)->insert($data);
        return $result;
    }
    //复制角色
    public static function privilege($companyId, $fromCompanyId)
    {
        $nowTime        = $_SERVER['REQUEST_TIME'];
        $where          = ['company_id'=>$fromCompanyId];
        $list           = Privilege::getList($where)->toArray();
        $data           = [];
        foreach( $list as $key=>$val )
        {
            $arr                  = $val;
            unset($arr['id']);
            $arr['copy_id']     = $val['id'];
            $arr['company_id']  = $companyId;
            $arr['created_at']  = $nowTime;
            $arr['updated_at']  = $nowTime;
            $data[]              = $arr;
        }
        $table          = 'ygt_privilege';
        DB::table($table)->where('company_id', $companyId)->delete();
        $result         = DB::table($table)->insert($data);
        self::privilegeAppindex($companyId);
        self::privilegeAppnode($companyId);
        return $result;
    }
    //复制角色工作页面的按钮
    public static function privilegeAppindex($companyId)
    {
        $arrData                = self::getPrivilegeIdArr($companyId);
        $idArr                  = $arrData['id_arr'];
        $newIdArr               = $arrData['new_id_arr'];
        $copyIdArr              = $arrData['copy_id_arr'];
        $lists                  = self::getAppindexList($copyIdArr);
        $nowTime                = $_SERVER['REQUEST_TIME'];
        $data                   = [];
        foreach($lists as $key=>$val)
        {
            $valPrivilegeId       = $val['privilege_id'];
            $arr                  = $val;
            unset($arr['id']);
            $arr['privilege_id']= $idArr[$valPrivilegeId];
            $arr['created_at']  = $nowTime;
            $arr['updated_at']  = $nowTime;
            $data[]              = $arr;
        }
        $table              = 'ygt_privilege_appindex';
        $result             = DB::table($table)->insert($data);
        return $result;
    }
    //批量取角色id对应的工作页面按钮id
    public static function getAppindexList($privilegeIdArr)
    {
        $where              = ['privilege_id'=>['in',$privilegeIdArr]];
        $result             = PrivilegeAppindex::getList($where)->toArray();
        return $result;
    }
    //获取厂角色和其复制厂角色的id的对应关系
    public static function getPrivilegeIdArr($companyId)
    {
        $where                  = ['company_id'=>$companyId];
        $privilegeList          = Privilege::getList($where)->toArray();
        $idArr                  = $copyIdArr = $newIdArr = [];
        foreach( $privilegeList as $key=>$val )
        {
            $valId              = $val['id'];
            $valCopyId          = $val['copy_id'];
            if( $valCopyId != 0 )
            {
                $newIdArr[]             = $valId;
                $copyIdArr[]            = $valCopyId;
                $idArr[$valCopyId]      = $valId;
            }
        }
        $result                 =[
            'id_arr'=>$idArr,'copy_id_arr'=>$copyIdArr,'new_id_arr'=>$newIdArr
        ];
        return $result;
    }
    //复制角色相关节点功能
    public static function privilegeAppnode($companyId)
    {
        $arrData                = self::getPrivilegeIdArr($companyId);
        $idArr                  = $arrData['id_arr'];
        $newIdArr               = $arrData['new_id_arr'];
        $copyIdArr               = $arrData['copy_id_arr'];
        $lists                  = self::getAppnodeList($copyIdArr);
        $nowTime                = $_SERVER['REQUEST_TIME'];
        $data                   = [];
        foreach($lists as $key=>$val)
        {
            $valPrivilegeId       = $val['privilege_id'];
            $arr                  = $val;
            unset($arr['id']);
            $arr['privilege_id']= $idArr[$valPrivilegeId];
            $arr['created_at']  = $nowTime;
            $arr['updated_at']  = $nowTime;
            $data[]              = $arr;
        }
        $table              = 'ygt_privilege_appnode';
        $result             = DB::table($table)->insert($data);
        return $result;
    }
    //批量取角色id对应的相关节点功能id
    public static function getAppnodeList($privilegeIdArr)
    {
        $where              = ['privilege_id'=>['in',$privilegeIdArr]];
        $result             = PrivilegeAppnode::getList($where)->toArray();
        return $result;
    }
    //复制多个工艺
    public static function orderTypeMore($companyId, $fromCompanyId, $orderTypeId)
    {
        ProcessField::setCompanyFieldList($companyId,$fromCompanyId);
        $result         = false;
        foreach( $orderTypeId as $key=>$val )
        {
            $result     = self::orderType($companyId, $val);
        }
        return $result;
    }
    //复制单个工艺
    public static function orderType($companyId, $orderTypeId)
    {
        $where          = ['id'=>$orderTypeId];
        $info           = OrderType::getInfo( $where );
        $result         = false;
        if( $info )
        {
            $nowTime                = $_SERVER['REQUEST_TIME'];
            $data                   = $info->toArray();
            unset($data['id']);
            $data['company_id']   = $companyId;
            $data['category_id']   = 0;
            $data['created_at']   = $nowTime;
            $data['updated_at']   = $nowTime;
            $table                  = 'ygt_order_type';
            $newOrderTypeId         = DB::table($table)->insertGetId($data);
            $result                 = self::orderTypeProcess($orderTypeId, $newOrderTypeId, $companyId);
        }
        return $result;
    }
    //复制一个工艺里面的工序
    public static function orderTypeProcess($orderTypeId, $newOrderTypeId, $companyId)
    {
        $orderTypeProcessList   = self::getOrderTypeProcess($orderTypeId);
        if( empty($orderTypeProcessList) ){
            $result             = false;
        } else {
            $nowTime            = $_SERVER['REQUEST_TIME'];
            $data               = [];
            foreach($orderTypeProcessList as $key=>$val)
            {
                //取厂里复制的工序(注一个工艺里同一个工序可以出现多次这是放在循环里的原因)
                $where              = ['company_id'=>$companyId,'copy_id'=>['!=',0]];
                $copyCollection     = Process::getList($where);
                $copyList           = $copyCollection->toArray();
                $copyIdArr          = $copyNewIdArr = [];
                foreach($copyList as $k=>$v)
                {
                    $vId                      = $v['id'];
                    $vCopyId                  = $v['copy_id'];
                    $copyIdArr[]              = $vCopyId;
                    $copyNewIdArr[$vCopyId]   = $vId;
                }
                //复制工艺关联的工序
                $valProcessId               = $val['process_id'];
                if(in_array($valProcessId,$copyIdArr)){
                    $newProcessId           = $copyNewIdArr[$valProcessId];
                } else {
                    $newProcessId           = self::process($companyId, $valProcessId);
                }
                $arr                        = $val;
                unset($arr['id']);
                $arr['copy_id']           = $val['id'];
                $arr['ordertype_id']      = $newOrderTypeId;
                $arr['process_id']        = $newProcessId;
                $arr['created_at']        = $nowTime;
                $arr['updated_at']        = $nowTime;
                $data[]                     = $arr;
            }
            $table              = 'ygt_process_ordertype';
            $tempResult         = DB::table($table)->insert($data);
            $result             = true;
            //更新ygt_process_ordertype中的next_step值
            if( $tempResult )
            {
                $newOrderTypeProcessList    = self::getOrderTypeProcess($newOrderTypeId);
                $nextStepArr                = [];
                foreach($newOrderTypeProcessList as $key=>$val)
                {
                    $valId                  = $val['id'];
                    $copyId                 = $val['copy_id'];
                    $nextStepArr[$copyId]   = $valId;
                }
                //$tempData                   = [];
                foreach($newOrderTypeProcessList as $key=>$val)
                {
                    $valNextStep            = $val['next_step'];
                    if( $valNextStep == 0 ){
                        continue;
                    }
                    $valNextStepArr         = explode(',',$valNextStep);
                    $valNextStepArrSize     = count($valNextStepArr);
                    if($valNextStepArrSize==1){
                        $newNextStep       = 0;
                        if( isset($nextStepArr[$valNextStep]) ){
                            $newNextStep   = $nextStepArr[$valNextStep];
                        }
                    } else {
                        $newNextStepArr     = [];
                        foreach($valNextStepArr as $k=>$v)
                        {
                            $tempnewNextStep    = 0;
                            if( isset($nextStepArr[$v]) ){
                                $tempnewNextStep   = $nextStepArr[$v];
                            }
                            $newNextStepArr[]   = $tempnewNextStep;
                        }
                        $newNextStep        = implode(',',$newNextStepArr);
                    }
                    $tempData               = [ 'next_step'=>$newNextStep ];
                    $result         = DB::table($table)->where('id',$val['id'])->update($tempData);
                }
            } else {
                $result         = false;
            }
        }
        return $result;
    }
    //取一个工艺里面的包含的工序
    public static function getOrderTypeProcess( $orderTypeId )
    {
        $where          = ['ordertype_id'=>$orderTypeId];
        $collection     = ProcessOrdertype::getList($where);
        $result         = $collection->sortBy('step_number')->values()->toArray();
        return $result;
    }
    //复制一个工序
    public static function process($companyId, $processId)
    {
        $where              = ['id'=>$processId];
        $info               = Process::getInfo($where);
        $newProcessId       = 0;
        if( $info )
        {
            $nowTime                = $_SERVER['REQUEST_TIME'];
            $data                   = $info->toArray();
            unset($data['id']);
            $data['copy_id']      = $processId;
            $data['company_id']   = $companyId;
            $data['created_at']   = $nowTime;
            $data['updated_at']   = $nowTime;
            $table                  = 'ygt_process';
            $newProcessId           = DB::table($table)->insertGetId($data);
            self::processFieldRelation($processId, $newProcessId);
        }
        return $newProcessId;
    }
    //复制工序字段
    public static function processFieldRelation($processId, $newProcessId)
    {
        $nowTime        = $_SERVER['REQUEST_TIME'];
        $lists          = self::getProcessFieldRelationList($processId);
        $data           = [];
        foreach( $lists as $key=>$val )
        {
            $arr                      = $val;
            unset($arr['id']);
            $arr['process_id']      = $newProcessId;
            $arr['created_at']      = $nowTime;
            $arr['updated_at']      = $nowTime;
            $data[]                   = $arr;
        }
        $table          = 'ygt_process_field_relation';
        $result         = DB::table($table)->insert($data);
        $newLists       = self::getProcessFieldRelationList($newProcessId);
        self::processFieldRelationSelect($lists,$newLists);
        return $result;
    }
    // 取一个工序的相关字段
    public static function getProcessFieldRelationList( $processId )
    {
        $where          = ['process_id'=>$processId];
        $result         = ProcessFieldRelation::getList($where)->toArray();
        return $result;
    }
    //复制工序字段下拉相关
    public static function processFieldRelationSelect( $lists,$newLists )
    {

        $nowTime                = $_SERVER['REQUEST_TIME'];
        $relationIdArr          = collect($lists)->pluck('id')->toArray();
        $fieldIdAndId           = collect($lists)->pluck('field_id','id')->toArray();
        $relationIdArrNew       = collect($newLists)->pluck('id')->toArray();
        $fieldIdAndIdNew        = collect($newLists)->pluck('id','field_id')->toArray();
        $where                  = ['relation_id'=>['in',$relationIdArr]];
        $selectListCollection   = ProcessFieldRelationSelect::getList($where);
        $selectList             = $selectListCollection->toArray();
        $data                   = [];
        foreach( $selectList as $key=>$val )
        {
            $valId                    = $val['id'];
            $valPid                   = $val['pid'];
            if( $valPid == 0 )
            {
                $valRelationId            = $val['relation_id'];
                $fieldId                  = $fieldIdAndId[$valRelationId];
                $newRelationId            = $fieldIdAndIdNew[$fieldId];
                $arr                      = $val;
                unset($arr['id']);
                $arr['copy_id']         = $valId;
                $arr['relation_id']     = $newRelationId;
                $arr['created_at']      = $nowTime;
                $arr['updated_at']      = $nowTime;
                $data[]                  = $arr;
            }
        }
        $table                      = 'ygt_process_field_relation_select';
        DB::table($table)->insert($data);
        $where                      = ['relation_id'=>['in',$relationIdArrNew]];
        $selectListCollectionNew    = ProcessFieldRelationSelect::getList($where);
        $selectListArr              = $selectListCollectionNew->pluck('id','copy_id')->toArray();
        $data                       = [];
        foreach( $selectList as $key=>$val )
        {
            $valPid                   = $val['pid'];
            if( $valPid != 0 )
            {
                $newPid                  = $selectListArr[$valPid];
                $valRelationId            = $val['relation_id'];
                $fieldId                  = $fieldIdAndId[$valRelationId];
                $newRelationId            = $fieldIdAndIdNew[$fieldId];
                $arr                      = $val;
                unset($arr['id']);
                $arr['pid']              = $newPid;
                $arr['relation_id']     = $newRelationId;
                $arr['created_at']      = $nowTime;
                $arr['updated_at']      = $nowTime;
                $data[]                  = $arr;
            }
        }
        DB::table($table)->insert($data);
    }

    public static function product($companyId, $fromCompanyId,$pid = 2, $newPid = 2){
        $companyWhere = ['company_id'=>$fromCompanyId];
        $categoryWhere = array_merge($companyWhere,['pid'=>$pid]);
        $category = Category::getData($categoryWhere,'','','',['id','asc'])->toArray();
        foreach ($category as $val){
            $categoryId = $val['id'];
            unset($val['id']);
            $val['company_id'] = $companyId;
            $val['pid'] = $newPid;
            $newCategoryId = Category::insertOneData($val,'id');

            //分类自定义设置字段
            $categoryFieldsWhere = ['category_id'=>$categoryId];
            $categoryFields = CategoryFields::getData($categoryFieldsWhere,'','','',['id','asc'])->toArray();
            foreach ($categoryFields as $categoryFieldsVal){
                unset($categoryFieldsVal['id']);
                $categoryFieldsVal['category_id'] = $newCategoryId;
                $newCategoryFieldsId = CategoryFields::insertOneData($categoryFieldsVal,'id');
            }

            //材料
            $productWhere = array_merge($companyWhere,['category_id'=>$categoryId]);
            $product = AssemblageMaterial::getData($productWhere,'','','',['id','asc'])->toArray();
            foreach ($product as $proVal){
                $productId = $proVal['id'];
                unset($proVal['id']);
                $proVal['company_id'] = $companyId;
                $proVal['category_id'] = $newCategoryId;
                $proVal['product_no'] = EngineProduct::createAssemblageMaterialNo();
                $proVal['number'] = 0;
                $proVal['price'] = 0;
                $newProductId = AssemblageMaterial::insertOneData($proVal,'id');

                //材料自定义字段
                $productFieldsWhere = ['assemblage_material_id'=>$productId];
                $productFields = ProductFields::getData($productFieldsWhere,'','','',['id','asc'])->toArray();
                foreach ($productFields as $productFieldsVal){
                    unset($productFieldsVal['id']);
                    $productFieldsVal['assemblage_material_id'] = $newProductId;
                    $newproductFieldsId = ProductFields::insertOneData($productFieldsVal,'id');
                }
            }

            self::product($companyId, $fromCompanyId, $categoryId, $newCategoryId);

        }
        return true;
    }

    public static function productOld($companyId, $fromCompanyId, $pid = 2, $newPid = 2){
        $companyWhere = ['company_id'=>$fromCompanyId];
        $categoryWhere = array_merge($companyWhere,['pid'=>$pid]);
        $category = Category::getData($categoryWhere)->toArray();
        foreach ($category as $val){
            $categoryId = $val['id'];
            unset($val['id']);
            $val['company_id'] = $companyId;
            $val['pid'] = $newPid;
            $newCategoryId = Category::insertOneData($val,'id');

            //分类自定义设置字段
            $categoryFieldsWhere = ['category_id'=>$categoryId];
            $categoryFields = CategoryFields::getData($categoryFieldsWhere)->toArray();
            foreach ($categoryFields as $categoryFieldsVal){
                unset($categoryFieldsVal['id']);
                $categoryFieldsVal['category_id'] = $newCategoryId;
                $newCategoryFieldsId = CategoryFields::insertOneData($categoryFieldsVal,'id');
            }

            //材料
            $productWhere = array_merge($companyWhere,['category_id'=>$categoryId]);
            $product = Product::getData($productWhere)->toArray();
            foreach ($product as $proVal){
                $productId = $proVal['id'];
                unset($proVal['id']);
                $proVal['company_id'] = $companyId;
                $proVal['category_id'] = $newCategoryId;
                $proVal['product_no'] = EngineProduct::createProductNo();
                $newProductId = Product::insertOneData($proVal,'id');

                //材料自定义字段
                $productFieldsWhere = ['product_id'=>$productId];
                $productFields = ProductFields::getData($productFieldsWhere,'','','',['id','asc'])->toArray();
                foreach ($productFields as $productFieldsVal){
                    unset($productFieldsVal['id']);
                    $productFieldsVal['product_id'] = $newProductId;
                    $newproductFieldsId = ProductFields::insertOneData($productFieldsVal,'id');
                }
            }

            self::product($companyId, $fromCompanyId, $categoryId, $newCategoryId);

        }
        return true;
    }
}